package com.sanri.tools.modules.mock.l7.http.service.interceptors;

import com.sanri.tools.modules.mock.l7.http.service.dtos.ResponseConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static java.nio.charset.StandardCharsets.UTF_8;

@Service
@Slf4j
public class CallInterceptorClient {
    @Autowired
    private List<ResponseInterceptor> responseInterceptors = new ArrayList<>();

    /**
     * 拦截器调用主方法
     * @param request
     * @param response
     * @param responseConfig
     */
    public void main(HttpServletRequest request, HttpServletResponse response, ResponseConfig responseConfig) throws IOException, DecoderException {
        // 可以根据不同的请求, 组装不同的 HandlerChain
        final HandlerChain handlerChain = new HandlerChain();
        for (ResponseInterceptor responseInterceptor : responseInterceptors) {
            if (responseInterceptor.match(request)){
                handlerChain.addInterceptorLast(responseInterceptor);
            }
        }

        IntermediateData intermediateData = new IntermediateData();
        intermediateData.setAttribute("request", request);
        handlerChain.interceptor(responseConfig, intermediateData);

        // 根据配置设置响应
        final ResponseConfig.ResponseDetail http = responseConfig.getResponseDetail();
        response.setStatus(http.getCode());
        if (StringUtils.isNotBlank(http.getLocale())) {
            response.setLocale(Locale.forLanguageTag(http.getLocale()));
        }

        final List<Map> headers = http.getHeaders();
        if (CollectionUtils.isNotEmpty(headers)){
            for (Map header : headers) {
                String name = (String) header.keySet().iterator().next();
                String value = (String) header.values().iterator().next();
                response.setHeader(name,value);

                // content-type 需要注意编码
                if (StringUtils.containsIgnoreCase(name,"content-type")){
                    final ContentType contentType = ContentType.parse(value);
                    contentType.withCharset(StandardCharsets.UTF_8);
                    response.setContentType(contentType.toString());
                    response.setHeader(name,contentType.toString());
                }
            }
        }

        String contentType = response.getContentType();
        if (StringUtils.isBlank(contentType)) {
            response.setContentType(ContentType.APPLICATION_JSON.withCharset(UTF_8).toString());
        }

        response.getWriter().write(http.getBody());
        response.getWriter().flush();
        response.getWriter().close();
//        response.getOutputStream().write(http.getBody().getBytes());
//        response.getOutputStream().flush();
//        response.getOutputStream().close();
    }
}
